/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.easemob.chatuidemo.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chatuidemo.widget.ExpandGridView;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.EMLog;
import com.easemob.util.NetUtils;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.User;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.FileUtils;
import net.mihome.app.common.ImageUtils;
import net.mihome.app.common.StringUtils;
import net.mihome.app.common.UIHelper;
import net.mihome.app.ui.FriendInfo;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.view.MiButton;
import net.mihome.app.widget.LoadingDialog;

import org.apache.http.Header;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class GroupDetailsActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = "GroupDetailsActivity";
    private static final int REQUEST_CODE_ADD_USER = 0;
    private static final int REQUEST_CODE_EXIT = 1;
    private static final int REQUEST_CODE_EXIT_DELETE = 2;
    private static final int REQUEST_CODE_CLEAR_ALL_HISTORY = 3;
    private static final int REQUEST_CODE_ADD_TO_BALCKLIST = 4;
    private static final int REQUEST_CODE_EDIT_GROUPNAME = 5;

    String longClickUsername = null;

    private ExpandGridView userGridview;
    private String groupId;
    private ProgressBar loadingPB;
    private Button exitBtn;
    private Button deleteBtn;
    private EMGroup group;
    private GridAdapter adapter;
    private int referenceWidth;
    private int referenceHeight;
    private List<User> userList = new ArrayList<User>();
    private RelativeLayout rl_switch_block_groupmsg;
    private InputMethodManager imm;
    LoadingDialog loadingDialog;
    private String theLarge;
    private String theThumbnail;
    private ImageView groupAvatar;
    private ProgressDialog progressDialog;
    /**
     * 屏蔽群消息imageView
     */
    private ImageView iv_switch_block_groupmsg;
    /**
     * 关闭屏蔽群消息imageview
     */
    private ImageView iv_switch_unblock_groupmsg;

    public static GroupDetailsActivity instance;

    // 清空所有聊天记录
    private RelativeLayout clearAllHistory;
    private RelativeLayout blacklistLayout;
    private RelativeLayout changeGroupNameLayout;
//    private RelativeLayout changeGroupAvatarLayout;

    private final static int GROUP_AVATAR_CHOICE_SDCARD=101;  //从sd卡中取图片
    private final static int GROUP_AVATAR_CHOICE_CANMA=102;   //照相机

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_details);
        instance = this;
        clearAllHistory = (RelativeLayout) findViewById(R.id.clear_all_history);
        userGridview = (ExpandGridView) findViewById(R.id.gridview);
        loadingPB = (ProgressBar) findViewById(R.id.progressBar);
        exitBtn = (Button) findViewById(R.id.btn_exit_grp);
        deleteBtn = (Button) findViewById(R.id.btn_exitdel_grp);
        blacklistLayout = (RelativeLayout) findViewById(R.id.rl_blacklist);
        changeGroupNameLayout = (RelativeLayout) findViewById(R.id.rl_change_group_name);
//        changeGroupAvatarLayout = (RelativeLayout) findViewById(R.id.rl_change_group_avatar);

        rl_switch_block_groupmsg = (RelativeLayout) findViewById(R.id.rl_switch_block_groupmsg);

        iv_switch_block_groupmsg = (ImageView) findViewById(R.id.iv_switch_block_groupmsg);
        iv_switch_unblock_groupmsg = (ImageView) findViewById(R.id.iv_switch_unblock_groupmsg);

        groupAvatar= (ImageView) findViewById(R.id.avatar);
        rl_switch_block_groupmsg.setOnClickListener(this);

        Drawable referenceDrawable = getResources().getDrawable(R.drawable.smiley_add_btn);
        referenceWidth = referenceDrawable.getIntrinsicWidth();
        referenceHeight = referenceDrawable.getIntrinsicHeight();

        // 获取传过来的groupid
        groupId = getIntent().getStringExtra("groupId");
        group = EMGroupManager.getInstance().getGroup(groupId);

        if(group!=null){
            ((TextView)findViewById(R.id.name)).setText(group.getGroupName());
            ((TextView)findViewById(R.id.member_sum)).setText(group.getMembers().size()+"人");
            ((TextView)findViewById(R.id.desc)).setText(group.getDescription());
        }
        ImageLoader.getInstance().displayImage(URLs.MIHOME_GROUP_AVATAR+groupId+".jpg?_t="+System.currentTimeMillis(),groupAvatar,options);
        if (group.getOwner() == null || "".equals(group.getOwner())
                || !group.getOwner().equals(EMChatManager.getInstance().getCurrentUser())) {
            exitBtn.setVisibility(View.GONE);
            deleteBtn.setVisibility(View.GONE);
            blacklistLayout.setVisibility(View.GONE);
            changeGroupNameLayout.setVisibility(View.GONE);
        }else{
            groupAvatar.setOnClickListener(this);
        }
        // 如果自己是群主，显示解散按钮
        if (EMChatManager.getInstance().getCurrentUser().equals(group.getOwner())) {
            exitBtn.setVisibility(View.GONE);
            deleteBtn.setVisibility(View.VISIBLE);
        }
        ((TextView) findViewById(R.id.group_name)).setText(group.getGroupName() + "(" + group.getAffiliationsCount() + "人)");
        adapter = new GridAdapter(this, R.layout.grid, userList);
        userGridview.setAdapter(adapter);

        // 保证每次进详情看到的都是最新的group
        updateGroup();

        // 设置OnTouchListener
        userGridview.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (adapter.isInDeleteMode) {
                            adapter.isInDeleteMode = false;
                            adapter.notifyDataSetChanged();
                            return true;
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
        // 软键盘管理类
        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        clearAllHistory.setOnClickListener(this);
        blacklistLayout.setOnClickListener(this);
        changeGroupNameLayout.setOnClickListener(this);
        getMembers(group);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(GroupDetailsActivity.this);
                progressDialog.setMessage("正在添加...");
                progressDialog.setCanceledOnTouchOutside(false);
            }
            switch (requestCode) {
                case REQUEST_CODE_ADD_USER:// 添加群成员
                    final String[] newmembers = data.getStringArrayExtra("newmembers");
                    progressDialog.show();
                    addMembersToGroup(newmembers);
                    break;
                case REQUEST_CODE_EXIT: // 退出群
                    progressDialog.setMessage("正在退出圈子...");
                    progressDialog.show();
                    exitGrop();
                    break;
                case REQUEST_CODE_EXIT_DELETE: // 解散群
                    progressDialog.setMessage("正在解散圈子...");
                    progressDialog.show();
                    deleteGrop();
                    break;
                case REQUEST_CODE_CLEAR_ALL_HISTORY:
                    // 清空此圈子的聊天记录
                    progressDialog.setMessage("正在清空群消息...");
                    progressDialog.show();
                    clearGroupHistory();
                    break;

                case REQUEST_CODE_EDIT_GROUPNAME: //修改群名称
                    final String returnData = data.getStringExtra("data");
                    if (!TextUtils.isEmpty(returnData)) {
                        progressDialog.setMessage("正在修改群名称...");
                        progressDialog.show();

                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    EMGroupManager.getInstance().changeGroupName(groupId, returnData);
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            ((TextView) findViewById(R.id.group_name)).setText(returnData + "(" + group.getAffiliationsCount()
                                                    + "人)");
                                            progressDialog.dismiss();
                                            Toast.makeText(getApplicationContext(), "修改群名称成功", Toast.LENGTH_SHORT).show();
                                        }
                                    });

                                } catch (EaseMobException e) {
                                    e.printStackTrace();
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            progressDialog.dismiss();
                                            Toast.makeText(getApplicationContext(), "改变群名称失败，请检查网络或稍后重试", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            }
                        }).start();
                    }
                    break;
                case REQUEST_CODE_ADD_TO_BALCKLIST:
                    progressDialog.setMessage("正在移入至黑名单");
                    progressDialog.show();
                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                EMGroupManager.getInstance().blockUser(groupId, longClickUsername);
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        adapter.notifyDataSetChanged();
                                        progressDialog.dismiss();
                                        Toast.makeText(getApplicationContext(), "移入黑名单成功", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            } catch (EaseMobException e) {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        progressDialog.dismiss();
                                        Toast.makeText(getApplicationContext(), "移入黑名单失败,请检查网络或稍后重试", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    }).start();

                    break;
                case GROUP_AVATAR_CHOICE_SDCARD:{
                    onActivityResult2(requestCode,resultCode,data);
                    break;
                }
                case GROUP_AVATAR_CHOICE_CANMA:{
                    onActivityResult2(requestCode,resultCode,data);
                    break;
                }
                default:
                    break;
            }
        }
    }

    /**
     * 点击退出群组按钮
     *
     * @param view
     */
    public void exitGroup(View view) {
        startActivityForResult(new Intent(this, ExitGroupDialog.class), REQUEST_CODE_EXIT);

    }

    /**
     * 点击解散群组按钮
     *
     * @param view
     */
    public void exitDeleteGroup(View view) {
        startActivityForResult(new Intent(this, ExitGroupDialog.class).putExtra("deleteToast", getString(R.string.dissolution_group_hint)),
                REQUEST_CODE_EXIT_DELETE);

    }

    /**
     * 清空圈子天记录
     */
    public void clearGroupHistory() {

        EMChatManager.getInstance().clearConversation(group.getGroupId());
        progressDialog.dismiss();
        // adapter.refresh(EMChatManager.getInstance().getConversation(toChatUsername));

    }

    /**
     * 退出群组
     */
    private void exitGrop() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMGroupManager.getInstance().exitFromGroup(groupId);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            setResult(RESULT_OK);
                            finish();
                            ChatActivity.activityInstance.finish();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), "退出圈子失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 解散群组
     */
    private void deleteGrop() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMGroupManager.getInstance().exitAndDeleteGroup(groupId);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            setResult(RESULT_OK);
                            finish();
                            ChatActivity.activityInstance.finish();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), "解散圈子失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 增加群成员
     *
     * @param newmembers
     */
    private void addMembersToGroup(final String[] newmembers) {
        new Thread(new Runnable() {

            public void run() {
                try {
                    // 创建者调用add方法
                    if (EMChatManager.getInstance().getCurrentUser().equals(group.getOwner())) {
                        EMGroupManager.getInstance().addUsersToGroup(groupId, newmembers);
                    } else {
                        // 一般成员调用invite方法
                        EMGroupManager.getInstance().inviteUser(groupId, newmembers, null);
                    }
                    runOnUiThread(new Runnable() {
                        public void run() {
                            adapter.notifyDataSetChanged();
                            ((TextView) findViewById(R.id.group_name)).setText(group.getGroupName() + "(" + group.getAffiliationsCount()
                                    + "人)");
                            progressDialog.dismiss();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), "添加群成员失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_switch_block_groupmsg: // 屏蔽群组
                if (iv_switch_block_groupmsg.getVisibility() == View.VISIBLE) {
                    System.out.println("change to unblock group msg");
                    try {
                        EMGroupManager.getInstance().unblockGroupMessage(groupId);
                        iv_switch_block_groupmsg.setVisibility(View.INVISIBLE);
                        iv_switch_unblock_groupmsg.setVisibility(View.VISIBLE);
                    } catch (Exception e) {
                        e.printStackTrace();
                        // todo: 显示错误给用户
                    }
                } else {
                    System.out.println("change to block group msg");
                    try {
                        EMGroupManager.getInstance().blockGroupMessage(groupId);
                        iv_switch_block_groupmsg.setVisibility(View.VISIBLE);
                        iv_switch_unblock_groupmsg.setVisibility(View.INVISIBLE);
                    } catch (Exception e) {
                        e.printStackTrace();
                        // todo: 显示错误给用户
                    }
                }
                break;

            case R.id.clear_all_history: // 清空聊天记录
                Intent intent = new Intent(GroupDetailsActivity.this, AlertDialog.class);
                intent.putExtra("cancel", true);
                intent.putExtra("titleIsCancel", true);
                intent.putExtra("msg", "确定清空此群的聊天记录吗？");
                startActivityForResult(intent, REQUEST_CODE_CLEAR_ALL_HISTORY);
                break;

            case R.id.rl_blacklist: // 黑名单列表
                startActivity(new Intent(GroupDetailsActivity.this, GroupBlacklistActivity.class).putExtra("groupId", groupId));
                break;

            case R.id.rl_change_group_name:
                startActivityForResult(new Intent(this, EditActivity.class).putExtra("data", group.getGroupName()), REQUEST_CODE_EDIT_GROUPNAME);
                break;
            case R.id.avatar: { //更换群头像
                // 隐藏软键盘
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                // 隐藏表情
                CharSequence[] items = {
                        GroupDetailsActivity.this.getString(R.string.img_from_album),
                        GroupDetailsActivity.this.getString(R.string.img_from_camera)};
                imageChooseItem(items);
                break;
            }
            default:
                break;
        }

    }

    /**
     * 群组成员gridadapter
     *
     * @author admin_new
     */
    private class GridAdapter extends ArrayAdapter<User> {

        private int res;
        public boolean isInDeleteMode;
        private List<User> objects;

        public GridAdapter(Context context, int textViewResourceId, List<User> objects) {
            super(context, textViewResourceId, objects);
            this.objects = objects;
            res = textViewResourceId;
            isInDeleteMode = false;
        }

        @Override
        public View getView(final int position, View convertView, final ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(res, null);
            }
            MiButton button = (MiButton) convertView.findViewById(R.id.button_avatar);
            // 最后一个item，减人按钮
            if (position == getCount() - 1) {
                button.setText("");
                // 设置成删除按钮
                button.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.smiley_minus_btn, 0, 0);
                // 如果不是创建者或者没有相应权限，不提供加减人按钮
                if (!group.getOwner().equals(EMChatManager.getInstance().getCurrentUser())) {
                    // if current user is not group admin, hide add/remove btn
                    convertView.setVisibility(View.INVISIBLE);
                } else { // 显示删除按钮
                    if (isInDeleteMode) {
                        // 正处于删除模式下，隐藏删除按钮
                        convertView.setVisibility(View.INVISIBLE);
                    } else {
                        // 正常模式
                        convertView.setVisibility(View.VISIBLE);
                        convertView.findViewById(R.id.badge_delete).setVisibility(View.INVISIBLE);
                    }
                    button.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            EMLog.d(TAG, "删除按钮被点击");
                            isInDeleteMode = true;
                            notifyDataSetChanged();
                        }
                    });
                }
            } else if (position == getCount() - 2) { // 添加群组成员按钮
                button.setText("");
                button.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.smiley_add_btn, 0, 0);
                // 如果不是创建者或者没有相应权限
                if (!group.isAllowInvites() && !group.getOwner().equals(EMChatManager.getInstance().getCurrentUser())) {
                    // if current user is not group admin, hide add/remove btn
                    convertView.setVisibility(View.INVISIBLE);
                } else {
                    // 正处于删除模式下,隐藏添加按钮
                    if (isInDeleteMode) {
                        convertView.setVisibility(View.INVISIBLE);
                    } else {
                        convertView.setVisibility(View.VISIBLE);
                        convertView.findViewById(R.id.badge_delete).setVisibility(View.INVISIBLE);
                    }
                    button.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            EMLog.d(TAG, "添加按钮被点击");
                            // 进入选人页面
                            try{
                                startActivityForResult((new Intent(GroupDetailsActivity.this, GroupPickContactsActivity.class).putExtra("groupId", groupId)),REQUEST_CODE_ADD_USER);
                            }catch ( Exception e){
                                e.printStackTrace();
                            }
                        }
                    });
                }
            } else { // 普通item，显示群组成员
                String showUserName = getItem(position).getRealName();
                if (showUserName == null || "".equals(showUserName.trim())) {
                    showUserName = getItem(position).getUsername();
                }
                final String username = getItem(position).getOpenId();
                button.setText(showUserName);
                convertView.setVisibility(View.VISIBLE);
                button.setVisibility(View.VISIBLE);
                Drawable avatar = getResources().getDrawable(R.drawable.default_avatar);
                avatar.setBounds(0, 0, referenceWidth, referenceHeight);
                button.setCompoundDrawables(null, avatar, null, null);
                // demo群组成员的头像都用默认头像，需由开发者自己去设置头像
                if (getItem(position).getFace() != null) {
                    button.setBackageFromHttp(getItem(position).getFace());
                }
                if (isInDeleteMode) {
                    // 如果是删除模式下，显示减人图标
                    convertView.findViewById(R.id.badge_delete).setVisibility(View.VISIBLE);
                } else {
                    convertView.findViewById(R.id.badge_delete).setVisibility(View.INVISIBLE);
                }
                button.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isInDeleteMode) {
                            // 如果是删除自己，return
                            if (EMChatManager.getInstance().getCurrentUser().equals(username)) {
                                startActivity(new Intent(GroupDetailsActivity.this, AlertDialog.class).putExtra("msg", "不能删除自己"));
                                return;
                            }
                            if (!NetUtils.hasNetwork(getApplicationContext())) {
                                Toast.makeText(getApplicationContext(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
                                return;
                            }
                            EMLog.d("group", "remove user from group:" + username);
                            deleteMembersFromGroup(username);
                        } else {
                            // 正常情况下点击user，可以进入用户详情或者聊天页面等等
                            // startActivity(new
                            // Intent(GroupDetailsActivity.this,
                            // ChatActivity.class).putExtra("userId",
                            // user.getUsername()));
                            Intent intent = new Intent(GroupDetailsActivity.this, FriendInfo.class);
                            intent.putExtra("uid", getItem(position).getUid());
                            startActivity(intent);
                        }
                    }

                    /**
                     * 删除群成员
                     *
                     * @param username
                     */
                    protected void deleteMembersFromGroup(final String username) {
                        final ProgressDialog deleteDialog = new ProgressDialog(GroupDetailsActivity.this);
                        deleteDialog.setMessage("正在移除...");
                        deleteDialog.setCanceledOnTouchOutside(false);
                        deleteDialog.show();
                        new Thread(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    // 删除被选中的成员
                                    EMGroupManager.getInstance().removeUserFromGroup(groupId, username);
                                    isInDeleteMode = false;
                                    runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            deleteDialog.dismiss();
                                            getMembers(group);
                                            notifyDataSetChanged();
                                            ((TextView) findViewById(R.id.group_name)).setText(group.getGroupName() + "("
                                                    + group.getAffiliationsCount() + "人)");
                                        }
                                    });
                                } catch (final Exception e) {
                                    deleteDialog.dismiss();
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            Toast.makeText(getApplicationContext(), "删除失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                                        }
                                    });
                                }

                            }
                        }).start();
                    }
                });

                button.setOnLongClickListener(new OnLongClickListener() {

                    @Override
                    public boolean onLongClick(View v) {
                        if (group.getOwner().equals(EMChatManager.getInstance().getCurrentUser())) {
                            Intent intent = new Intent(GroupDetailsActivity.this, AlertDialog.class);
                            intent.putExtra("msg", "确认将此成员加入至此群黑名单?");
                            intent.putExtra("cancel", true);
                            startActivityForResult(intent, REQUEST_CODE_ADD_TO_BALCKLIST);
                            longClickUsername = username;
                        }
                        return false;
                    }
                });
            }
            return convertView;
        }

        @Override
        public int getCount() {
            return super.getCount() + 2;
        }
    }

    protected void updateGroup() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMGroup returnGroup = EMGroupManager.getInstance().getGroupFromServer(groupId);
                    // 更新本地数据
                    EMGroupManager.getInstance().createOrUpdateLocalGroup(returnGroup);

                    runOnUiThread(new Runnable() {
                        public void run() {
                            ((TextView) findViewById(R.id.group_name)).setText(group.getGroupName() + "(" + group.getAffiliationsCount()
                                    + "人)");
                            loadingPB.setVisibility(View.INVISIBLE);
                            adapter.notifyDataSetChanged();
                            if (EMChatManager.getInstance().getCurrentUser().equals(group.getOwner())) {
                                // 显示解散按钮
                                exitBtn.setVisibility(View.GONE);
                                deleteBtn.setVisibility(View.VISIBLE);
                            } else {
                                // 显示退出按钮
                                exitBtn.setVisibility(View.VISIBLE);
                                deleteBtn.setVisibility(View.GONE);

                            }

                            // update block
                            System.out.println("group msg is blocked:" + group.getMsgBlocked());
                            if (group.getMsgBlocked()) {
                                iv_switch_block_groupmsg.setVisibility(View.VISIBLE);
                                iv_switch_unblock_groupmsg.setVisibility(View.INVISIBLE);
                            } else {
                                iv_switch_block_groupmsg.setVisibility(View.INVISIBLE);
                                iv_switch_unblock_groupmsg.setVisibility(View.VISIBLE);
                            }
                        }
                    });

                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            loadingPB.setVisibility(View.INVISIBLE);
                        }
                    });
                }
            }
        }).start();
    }

    public void back(View view) {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        instance = null;
    }

    /**
     * 从服务器获取到群成员信息
     */
    public void getMembers(EMGroup group) {
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setContentView(R.layout.loadingdialog);
        loadingDialog.show();
        RequestParams requestParams = new RequestParams();
        requestParams.add("group_id", group.getGroupId());
        AppContext.ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_USER_CHAT_GET_GROUP_MEMBERS, requestParams, new MiAsyncHttpResponseHandler<List<Map>>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<List<Map>> responsePojo) {
                List<User> list = User.parserList(responsePojo);
                userList.clear();
                userList.addAll(list);
//                adapter.notifyDataSetChanged();
                adapter = new GridAdapter(GroupDetailsActivity.this, R.layout.grid, userList);
                userGridview.setAdapter(adapter);
                if(list!=null){
                    ((TextView)findViewById(R.id.member_sum)).setText(list.size()+"");
                }else{
                    ((TextView)findViewById(R.id.member_sum)).setText(0+"");
                }
                loadingDialog.dismiss();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                arg3.printStackTrace();
                Toast.makeText(GroupDetailsActivity.this, "获取好友信息失败，请见检查网络", Toast.LENGTH_SHORT).show();
                loadingDialog.dismiss();
            }
        });
    }

    /**
     * 操作选择
     *
     * @param items
     */
    public void imageChooseItem(CharSequence[] items) {
        android.app.AlertDialog imageDialog = new android.app.AlertDialog.Builder(this)
                .setTitle(R.string.ui_insert_image)
                .setIcon(android.R.drawable.btn_star)
                .setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        // 手机选图
                        if (item == 0) {
                            Intent intent;
                            if (Build.VERSION.SDK_INT < 19) {
                                intent = new Intent();
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.setType("image/*");
                                startActivityForResult(
                                        Intent.createChooser(intent, "选择图片"),
                                        GROUP_AVATAR_CHOICE_SDCARD);
                            } else {
                                intent = new Intent(
                                        Intent.ACTION_PICK,
                                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                intent.setType("image/*");
                                startActivityForResult(
                                        Intent.createChooser(intent, "选择图片"),
                                        GROUP_AVATAR_CHOICE_SDCARD);
                            }
                        }
                        // 拍照
                        else if (item == 1) {
                            String savePath = "";
                            // 判断是否挂载了SD卡
                            String storageState = Environment
                                    .getExternalStorageState();
                            if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                                savePath = Environment
                                        .getExternalStorageDirectory()
                                        .getAbsolutePath()
                                        + "/OSChina/Camera/";// 存放照片的文件夹
                                File savedir = new File(savePath);
                                if (!savedir.exists()) {
                                    savedir.mkdirs();
                                }
                            }

                            // 没有挂载SD卡，无法保存文件
                            if (StringUtils.isEmpty(savePath)) {
                                UIHelper.ToastMessage(GroupDetailsActivity.this,
                                        "无法保存照片，请检查SD卡是否挂载");
                                return;
                            }

                            String timeStamp = new SimpleDateFormat(
                                    "yyyyMMddHHmmss").format(new Date());
                            String fileName = "osc_" + timeStamp + ".jpg";// 照片命名
                            File out = new File(savePath, fileName);
                            Uri uri = Uri.fromFile(out);

                            theLarge = savePath + fileName;// 该照片的绝对路径

                            Intent intent = new Intent(
                                    MediaStore.ACTION_IMAGE_CAPTURE);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                            startActivityForResult(intent,
                                    GROUP_AVATAR_CHOICE_CANMA);
                        }
                    }
                }).create();

        imageDialog.show();
    }

    /**
     * 处理图片,onActivityResult方法是在太长了，分出来做
     */

    public void onActivityResult2(final int requestCode, final int resultCode, final Intent imageReturnIntent) {
        progressDialog = new ProgressDialog(GroupDetailsActivity.this);
        progressDialog.setMessage("正在上传...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                progressDialog.dismiss();
                if (msg.what == 1 && msg.obj != null) {
                    // 显示图片
                    String imgUrl= (String) msg.obj+"?_id="+System.currentTimeMillis();
                    if(imgUrl!=null){
                        ImageLoader.getInstance().clearMemoryCache();
                        ImageLoader.getInstance().displayImage(imgUrl, groupAvatar);
                    }
                }else{
                    UIHelper.showAlertDialog(GroupDetailsActivity.this,"抱歉","圈子头像设置失败");
                }
            }
        };
        if (requestCode == GROUP_AVATAR_CHOICE_SDCARD) {
            //从sd卡中去照片
            Toast.makeText(this,"sd",Toast.LENGTH_SHORT).show();
        }else if (requestCode == GROUP_AVATAR_CHOICE_CANMA) {
            //拍照
            Toast.makeText(this,"照相机",Toast.LENGTH_SHORT).show();
        }
        new Thread(){
            private String selectedImagePath;
            @Override
            public void run() {
                Bitmap bitmap = null;
                if (requestCode == GROUP_AVATAR_CHOICE_SDCARD) {
                    if (imageReturnIntent == null)
                    {
                        return;
                    }
                    Uri selectedImageUri = imageReturnIntent.getData();
                    if (selectedImageUri != null) {
                        selectedImagePath = ImageUtils.getImagePath( selectedImageUri, GroupDetailsActivity.this);
                    }

                    if (selectedImagePath != null) {
                        theLarge = selectedImagePath;
                    } else {
                        bitmap = ImageUtils.loadPicasaImageFromGalley(selectedImageUri, GroupDetailsActivity.this);
                    }

                    if (AppContext.isMethodsCompat(android.os.Build.VERSION_CODES.ECLAIR_MR1)) {
                        String imaName = FileUtils.getFileName(theLarge);
                        if (imaName != null)
                            bitmap = ImageUtils.loadImgThumbnail(GroupDetailsActivity.this,
                                    imaName,
                                    MediaStore.Images.Thumbnails.MICRO_KIND);
                    }
                    if (bitmap == null && !StringUtils.isEmpty(theLarge))
                        bitmap = ImageUtils.loadImgThumbnail(theLarge, 100, 100);
                }else if (requestCode == GROUP_AVATAR_CHOICE_CANMA) {
                    if (bitmap == null && !StringUtils.isEmpty(theLarge)) {
                        bitmap = ImageUtils.loadImgThumbnail(theLarge, 100, 100);
                    }
                }
                if(bitmap!=null){
                    // 存放照片的文件夹
                    String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mihome/Camera/";
                    File savedir = new File(savePath);
                    if (!savedir.exists()) {
                        savedir.mkdirs();
                    }

                    String largeFileName = FileUtils.getFileName(theLarge);
                    String largeFilePath = savePath + largeFileName;
                    // 生成上传的800宽度图片
                    String thumbFileName = "thumb_" + largeFileName;
                    theThumbnail = savePath + thumbFileName;
                    Message msg = new Message();
                    try {
                        // 压缩上传的图片
                        File tFile=new File(theThumbnail);
                        if(tFile.exists()){
                            tFile.delete();
                            ImageLoader.getInstance().clearMemoryCache();
                        }
                        ImageUtils.createImageThumbnail(GroupDetailsActivity.this,theLarge, theThumbnail, 800, 80);
                        File imgFile = new File(theThumbnail);
                        String imageUrl=AppContext.getInstance().uploadImage(imgFile,groupId);
                        //imageFile可以作为上传
                        msg.what = 1;
                        msg.obj = imageUrl;
                        handler.sendMessage(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                        msg.what = -1;
                        handler.sendMessage(msg);
                    }
                }
                super.run();
            }
        }.start();
    }

    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.qunliao_common)
            .showImageForEmptyUri(R.drawable.qunliao_common) // resource or drawable
            .showImageOnFail(R.drawable.qunliao_common) // resource or drawable
            .resetViewBeforeLoading(false)  // default
            .cacheInMemory(false) // default
            .cacheOnDisk(true) // default
            .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
            .bitmapConfig(Bitmap.Config.ARGB_8888) // default
            .displayer(new SimpleBitmapDisplayer()) // default
            .handler(new Handler()) // default
            .build();

    DisplayImageOptions optionsFriend = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.contact_common)
            .showImageForEmptyUri(R.drawable.contact_common) // resource or drawable
            .showImageOnFail(R.drawable.contact_common) // resource or drawable
            .resetViewBeforeLoading(false)  // default
            .cacheInMemory(false) // default
            .cacheOnDisk(true) // default
            .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
            .bitmapConfig(Bitmap.Config.ARGB_8888) // default
            .displayer(new SimpleBitmapDisplayer()) // default
            .handler(new Handler()) // default
            .build();
}
